import React, { useState } from 'react';
import { Card, Tabs, List, Avatar, Badge, Button, Input, Tag, Modal, Empty } from 'antd';
import type { TabsProps } from 'antd';
import { SearchOutlined, StarOutlined, DeleteOutlined, CheckOutlined } from '@ant-design/icons';

const { Search } = Input;

// 模拟通知数据
interface NotificationItem {
  id: string;
  title: string;
  content: string;
  type: 'system' | 'business' | 'marketing' | 'warning';
  isRead: boolean;
  isStarred: boolean;
  time: string;
  avatar?: string;
}

// 模拟消息数据
interface MessageItem {
  id: string;
  from: string;
  content: string;
  isRead: boolean;
  time: string;
  avatar: string;
}

// 模拟通知数据
const notificationData: NotificationItem[] = [
  {
    id: '1',
    title: '系统维护通知',
    content: '系统将于2023年6月15日凌晨2:00-4:00进行例行维护，请提前做好准备。',
    type: 'system',
    isRead: false,
    isStarred: false,
    time: '2023-06-10 14:30'
  },
  {
    id: '2',
    title: '订单状态更新',
    content: '您有3个订单已完成发货，订单号分别为：OD20230610001、OD20230610002、OD20230610003。',
    type: 'business',
    isRead: false,
    isStarred: true,
    time: '2023-06-10 10:15'
  },
  {
    id: '3',
    title: '新功能上线通知',
    content: '系统新增了数据导出功能，您可以在报表页面使用此功能导出各类数据报表。',
    type: 'system',
    isRead: true,
    isStarred: false,
    time: '2023-06-09 16:45'
  },
  {
    id: '4',
    title: '营销活动通知',
    content: '618年中大促即将开始，提前了解活动详情，准备营销方案。',
    type: 'marketing',
    isRead: true,
    isStarred: false,
    time: '2023-06-08 09:30'
  },
  {
    id: '5',
    title: '数据异常警告',
    content: '系统检测到您的部分销售数据存在异常波动，建议及时查看并处理。',
    type: 'warning',
    isRead: false,
    isStarred: true,
    time: '2023-06-07 15:20'
  },
];

// 模拟消息数据
const messageData: MessageItem[] = [
  {
    id: '1',
    from: '张三',
    content: '关于下季度的销售计划，我们需要安排一次会议讨论具体细节。',
    isRead: false,
    time: '2023-06-10 15:45',
    avatar: 'https://joeschmoe.io/api/v1/random?name=张三'
  },
  {
    id: '2',
    from: '李四',
    content: '您提交的报表已经审核通过，可以在系统中查看最终版本。',
    isRead: false,
    time: '2023-06-10 11:20',
    avatar: 'https://joeschmoe.io/api/v1/random?name=李四'
  },
  {
    id: '3',
    from: '王五',
    content: '客户反馈系统响应速度较慢，我们需要检查一下服务器性能。',
    isRead: true,
    time: '2023-06-09 17:30',
    avatar: 'https://joeschmoe.io/api/v1/random?name=王五'
  },
  {
    id: '4',
    from: '系统管理员',
    content: '您的账户安全等级较低，建议开启两步验证以提高安全性。',
    isRead: true,
    time: '2023-06-08 14:15',
    avatar: 'https://joeschmoe.io/api/v1/random?name=系统管理员'
  },
];

const MessageCenterPage: React.FC = () => {
  // 状态管理
  const [notifications, setNotifications] = useState<NotificationItem[]>(notificationData);
  const [messages, setMessages] = useState<MessageItem[]>(messageData);
  const [selectedNotification, setSelectedNotification] = useState<NotificationItem | null>(null);
  const [selectedMessage, setSelectedMessage] = useState<MessageItem | null>(null);
  const [notificationModalVisible, setNotificationModalVisible] = useState(false);
  const [messageModalVisible, setMessageModalVisible] = useState(false);
  const [currentTabKey, setCurrentTabKey] = useState('1');

  // 获取未读通知数量
  const unreadNotificationCount = notifications.filter(item => !item.isRead).length;
  
  // 获取未读消息数量
  const unreadMessageCount = messages.filter(item => !item.isRead).length;

  // 处理通知类型标签
  const getNotificationTypeTag = (type: string) => {
    switch (type) {
      case 'system':
        return <Tag color="blue">系统通知</Tag>;
      case 'business':
        return <Tag color="green">业务通知</Tag>;
      case 'marketing':
        return <Tag color="orange">营销通知</Tag>;
      case 'warning':
        return <Tag color="red">警告通知</Tag>;
      default:
        return <Tag>其他</Tag>;
    }
  };

  // 处理通知点击
  const handleNotificationClick = (item: NotificationItem) => {
    setSelectedNotification(item);
    setNotificationModalVisible(true);
    
    // 标记为已读
    if (!item.isRead) {
      setNotifications(prev => 
        prev.map(notification => 
          notification.id === item.id ? { ...notification, isRead: true } : notification
        )
      );
    }
  };

  // 处理消息点击
  const handleMessageClick = (item: MessageItem) => {
    setSelectedMessage(item);
    setMessageModalVisible(true);
    
    // 标记为已读
    if (!item.isRead) {
      setMessages(prev => 
        prev.map(message => 
          message.id === item.id ? { ...message, isRead: true } : message
        )
      );
    }
  };

  // 处理收藏/取消收藏通知
  const handleToggleStarNotification = (e: React.MouseEvent, item: NotificationItem) => {
    e.stopPropagation();
    setNotifications(prev => 
      prev.map(notification => 
        notification.id === item.id ? { ...notification, isStarred: !notification.isStarred } : notification
      )
    );
  };

  // 处理删除通知
  const handleDeleteNotification = (e: React.MouseEvent, item: NotificationItem) => {
    e.stopPropagation();
    setNotifications(prev => prev.filter(notification => notification.id !== item.id));
  };

  // 处理删除消息
  const handleDeleteMessage = (e: React.MouseEvent, item: MessageItem) => {
    e.stopPropagation();
    setMessages(prev => prev.filter(message => message.id !== item.id));
  };

  // 标记所有为已读
  const handleMarkAllAsRead = () => {
    if (currentTabKey === '1') {
      setNotifications(prev => prev.map(notification => ({ ...notification, isRead: true })));
    } else {
      setMessages(prev => prev.map(message => ({ ...message, isRead: true })));
    }
  };

  // 标签页配置
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: (
        <Badge count={unreadNotificationCount} showZero>
          <span>通知中心</span>
        </Badge>
      ),
      children: (
        <Card variant="outlined" extra={<Button type="link" onClick={handleMarkAllAsRead}>全部标记为已读</Button>}>
          <Search
            placeholder="搜索通知"
            allowClear
            style={{ marginBottom: 16, width: 240 }}
            prefix={<SearchOutlined />}
          />
          
          {notifications.length > 0 ? (
            <List
              itemLayout="vertical"
              dataSource={notifications}
              renderItem={(item) => (
                <List.Item 
                  key={item.id} 
                  className={item.isRead ? 'notification-item-read' : 'notification-item-unread'}
                  style={{
                    borderBottom: '1px solid #f0f0f0',
                    padding: '16px 0',
                    cursor: 'pointer',
                    backgroundColor: item.isRead ? 'transparent' : '#e6f7ff'
                  }}
                  onClick={() => handleNotificationClick(item)}
                  actions={[
                    <Button 
                      type="text" 
                      key="star" 
                      icon={item.isStarred ? <StarOutlined style={{ color: '#ff9800' }} /> : <StarOutlined />}
                      onClick={(e) => handleToggleStarNotification(e, item)}
                    />,
                    <Button 
                      type="text" 
                      key="delete" 
                      icon={<DeleteOutlined />} 
                      danger
                      onClick={(e) => handleDeleteNotification(e, item)}
                    />
                  ]}
                >
                  <List.Item.Meta
                    title={
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <span style={{ fontWeight: item.isRead ? 'normal' : 'bold' }}>{item.title}</span>
                        <span style={{ fontSize: 12, color: '#999' }}>{item.time}</span>
                      </div>
                    }
                    description={
                      <div>
                        {getNotificationTypeTag(item.type)}
                        <p style={{ marginTop: 8, color: '#666' }}>{item.content}</p>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          ) : (
            <Empty description="暂无通知" />
          )}
        </Card>
      ),
    },
    {
      key: '2',
      label: (
        <Badge count={unreadMessageCount} showZero>
          <span>站内消息</span>
        </Badge>
      ),
      children: (
        <Card variant="outlined" extra={<Button type="link" onClick={handleMarkAllAsRead}>全部标记为已读</Button>}>
          <Search
            placeholder="搜索消息"
            allowClear
            style={{ marginBottom: 16, width: 240 }}
            prefix={<SearchOutlined />}
          />
          
          {messages.length > 0 ? (
            <List
              itemLayout="horizontal"
              dataSource={messages}
              renderItem={(item) => (
                <List.Item 
                  key={item.id} 
                  className={item.isRead ? 'message-item-read' : 'message-item-unread'}
                  style={{
                    borderBottom: '1px solid #f0f0f0',
                    padding: '16px 0',
                    cursor: 'pointer',
                    backgroundColor: item.isRead ? 'transparent' : '#e6f7ff'
                  }}
                  onClick={() => handleMessageClick(item)}
                >
                  <List.Item.Meta
                    avatar={<Avatar src={item.avatar} />}
                    title={
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <span style={{ fontWeight: item.isRead ? 'normal' : 'bold' }}>{item.from}</span>
                        <span style={{ fontSize: 12, color: '#999' }}>{item.time}</span>
                      </div>
                    }
                    description={
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <p style={{ margin: 0, color: '#666', width: 'calc(100% - 60px)' }}>{item.content}</p>
                        <Button 
                          type="text" 
                          icon={<DeleteOutlined />} 
                          danger
                          onClick={(e) => handleDeleteMessage(e, item)}
                          style={{ marginLeft: '16px' }}
                        />
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          ) : (
            <Empty description="暂无消息" />
          )}
        </Card>
      ),
    },
  ];

  return (
    <div>
      <h1 style={{ marginBottom: '24px' }}>消息中心</h1>
      <Tabs 
        items={items} 
        onChange={(key) => setCurrentTabKey(key)} 
        activeKey={currentTabKey}
      />
      
      {/* 通知详情模态框 */}
      <Modal
        title={selectedNotification?.title || '通知详情'}
        open={notificationModalVisible}
        onCancel={() => setNotificationModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedNotification && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
              {getNotificationTypeTag(selectedNotification.type)}
              <span style={{ fontSize: 12, color: '#999' }}>{selectedNotification.time}</span>
            </div>
            <div style={{ fontSize: 16, lineHeight: 1.8, color: '#333', whiteSpace: 'pre-line' }}>
              {selectedNotification.content}
            </div>
            <div style={{ marginTop: 24, textAlign: 'right' }}>
              <Button type="primary" onClick={() => setNotificationModalVisible(false)}>
                <CheckOutlined /> 已阅
              </Button>
            </div>
          </div>
        )}
      </Modal>
      
      {/* 消息详情模态框 */}
      <Modal
        title={`来自 ${selectedMessage?.from || ''} 的消息`}
        open={messageModalVisible}
        onCancel={() => setMessageModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedMessage && (
          <div>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
              <Avatar src={selectedMessage.avatar} size={48} style={{ marginRight: 16 }} />
              <div>
                <div style={{ fontSize: 18, fontWeight: 'bold' }}>{selectedMessage.from}</div>
                <div style={{ fontSize: 12, color: '#999' }}>{selectedMessage.time}</div>
              </div>
            </div>
            <div style={{ fontSize: 16, lineHeight: 1.8, color: '#333', whiteSpace: 'pre-line', padding: '16px', backgroundColor: '#f5f5f5', borderRadius: 4 }}>
              {selectedMessage.content}
            </div>
            <div style={{ marginTop: 24, textAlign: 'right' }}>
              <Button type="primary" onClick={() => setMessageModalVisible(false)}>
                <CheckOutlined /> 已阅
              </Button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default MessageCenterPage;